package com.aia.ann.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

import com.aia.ann.ahead.AnnConstant;
import com.aia.ann.domain.Agent;
import com.aia.ann.domain.AgentExample;
import com.aia.ann.domain.AgentKey;
import com.aia.ann.domain.Deleted;
import com.aia.ann.domain.DeletedWithBLOBs;
import com.aia.ann.domain.Demopic;
import com.aia.ann.domain.DemopicExample;
import com.aia.ann.domain.Insu;
import com.aia.ann.domain.InsuExample;
import com.aia.ann.domain.Postcard;
import com.aia.ann.domain.PostcardWithBLOBs;
import com.aia.ann.domain.Smartinfo;
import com.aia.ann.domain.SmartinfoExample;
import com.aia.ann.domain.Trace;
import com.aia.ann.persistence.dao.AgentDAO;
import com.aia.ann.persistence.dao.DeletedDAO;
import com.aia.ann.persistence.dao.DemopicDAO;
import com.aia.ann.persistence.dao.InsuDAO;
import com.aia.ann.persistence.dao.PostcardDAO;
import com.aia.ann.persistence.dao.SmartinfoDAO;
import com.aia.ann.persistence.dao.TraceDAO;
import com.aia.ann.web.MomentListAction;
import com.aia.ann.web.ProtectionResultAction;
import com.aia.ann.web.json.AgentJson;
import com.aia.ann.web.json.AnnChangeJson;
import com.aia.ann.web.json.AnnCreateInsuJson;
import com.aia.ann.web.json.AnnSendMailJson;
import com.aia.ann.web.json.AnnSmartInfoJson;
import com.aia.ann.web.json.AnnUpdateInsuJson;
import com.aia.ann.web.json.CustomerTestDemopic01Json;
import com.aia.ann.web.json.CustomerTestDemopic03Json;
import com.aia.ann.web.json.DemopicJson;
import com.aia.ann.web.json.DemopicJson02;
import com.aia.ann.web.sanity.Testann01Action;
import com.aia.ann.web.sanity.Testann03Action;
import com.aia.ann.web.xml.AnnAgentXml;
import com.aia.ann.web.xml.AnnUploadXml;
import com.aia.ann.web.xml.AnnUploadXml2;
import com.aia.ann.web.xml.AnnVisitCountXml;
import com.aia.ilp.domain.SmsLog;
import com.aia.ilp.domain.SmsLogExample;
import com.aia.ilp.persistence.dao.SmsLogDAO;
import com.aia.ilp.persistence.dao.SmsMsgchosendDAO;
import com.aia.ilp.web.json.CustomerSmsJson;
import com.cfh.ahead.Constant;
import com.cfh.ahead.SequenceNameProvider;
import com.cfh.domain.Sequence;
import com.cfh.persistence.dao.SequenceDAO;
import com.cfh.util.Tools;
import com.cfh.util.XmlStringBuffer;
import com.cfh.web.PageBean;
import com.sun.mail.smtp.SMTPSendFailedException;

public class ChiefServiceImpl implements ChiefService {
	private static final Logger logger = Logger.getLogger(ChiefServiceImpl.class);
	private JdbcTemplate jdbcTemplate;
	
	private SmsMsgchosendDAO smsMsgchosendDAO;
	
	public SmsMsgchosendDAO getSmsMsgchosendDAO() {
		return smsMsgchosendDAO;
	}
	
	public void setSmsMsgchosendDAO(SmsMsgchosendDAO smsMsgchosendDAO) {
		this.smsMsgchosendDAO = smsMsgchosendDAO;
	}
	
	private SmsLogDAO smsLogDAO;
	
	public SmsLogDAO getSmsLogDAO() {
		return smsLogDAO;
	}
	
	public void setSmsLogDAO(SmsLogDAO smsLogDAO) {
		this.smsLogDAO = smsLogDAO;
	}
	
	private TraceDAO traceDAO;

	public TraceDAO getTraceDAO() {
		return traceDAO;
	}

	public void setTraceDAO(TraceDAO traceDAO) {
		this.traceDAO = traceDAO;
	}

	private PostcardDAO postcardDAO;

	public PostcardDAO getPostcardDAO() {
		return postcardDAO;
	}

	public void setPostcardDAO(PostcardDAO postcardDAO) {
		this.postcardDAO = postcardDAO;
	}

	private DeletedDAO deletedDAO;

	public DeletedDAO getDeletedDAO() {
		return deletedDAO;
	}

	public void setDeletedDAO(DeletedDAO deletedDAO) {
		this.deletedDAO = deletedDAO;
	}

	private AgentDAO agentDAO;

	public void setAgentDAO(AgentDAO agentDAO) {
		this.agentDAO = agentDAO;
	}

	public AgentDAO getAgentDAO() {
		return agentDAO;
	}

	private SmartinfoDAO smartinfoDAO;

	public void setSmartinfoDAO(SmartinfoDAO smartinfoDAO) {
		this.smartinfoDAO = smartinfoDAO;
	}

	public SmartinfoDAO getSmartinfoDAO() {
		return smartinfoDAO;
	}

	private DemopicDAO demopicDAO;

	public void setDemopicDAO(DemopicDAO demopicDAO) {
		this.demopicDAO = demopicDAO;
	}

	public DemopicDAO getDemopicDAO() {
		return demopicDAO;
	}

	private SequenceDAO sequenceDAO;

	public void setSequenceDAO(SequenceDAO sequenceDAO) {
		this.sequenceDAO = sequenceDAO;
	}

	public SequenceDAO getSequenceDAO() {
		return sequenceDAO;
	}

	private SequenceNameProvider sequenceNameProvider;

	public void setSequenceNameProvider(SequenceNameProvider sequenceNameProvider) {
		this.sequenceNameProvider = sequenceNameProvider;
	}

	public SequenceNameProvider getSequenceNameProvider() {
		return sequenceNameProvider;
	}

	private InsuDAO insuDAO;

	public void setInsuDAO(InsuDAO insuDAO) {
		this.insuDAO = insuDAO;
	}

	public InsuDAO getInsuDAO() {
		return insuDAO;
	}

	public void junitInsertDemopic(Demopic record) {
		demopicDAO.insert(record);
	}

	public void testann01(Testann01Action testann01Action) {
		if (logger.isDebugEnabled()) {
			logger.debug("testann01(Testann01Action) - start"); //$NON-NLS-1$
		}
		{// validate
			if (Tools.isEmpty(testann01Action.getEID())) {
				testann01Action.addActionError("EID is empty");
				return;
			}
		}
		{// do some code2
			Demopic dp = demopicDAO.selectByPrimaryKey(testann01Action.getEID());
			if (dp == null) {
				if (logger.isDebugEnabled()) {
					logger.debug("no records found:" + testann01Action.getEID()); //$NON-NLS-1$
				}
				testann01Action.addActionError("no records found:" + testann01Action.getEID());
				return;
			} else {
				if (logger.isDebugEnabled()) {
					logger.debug(testann01Action.getEID() + " FOUND!"); //$NON-NLS-1$
				}
				testann01Action.addActionMessage(testann01Action.getEID() + " FOUND!");
			}

			if (logger.isDebugEnabled()) {
				logger.debug("testann01(Testann01Action) - end"); //$NON-NLS-1$
			}
			return;
		}
	}

	public void testann03(Testann03Action testann03Action) {
		if (logger.isDebugEnabled()) {
			logger.debug("testann03(Testann03Action) - start");
		}
		{// validate
			if (Tools.isEmpty(testann03Action.getEID())) {
				testann03Action.addActionError("EID is empty");
				return;
			}
		}
		{
			Demopic dp = demopicDAO.selectByPrimaryKey(testann03Action.getEID());
			if (dp == null) {
				if (logger.isDebugEnabled()) {
					logger.debug("No records found:" + testann03Action.getEID());
				}
				testann03Action.addActionError("No records found:" + testann03Action.getEID());
				return;
			} else {
				if (logger.isDebugEnabled()) {
					logger.debug(testann03Action.getEID() + "Found!");
				}
				testann03Action.addActionMessage(testann03Action.getEID() + "Found!");
			}
		}
		{
			if (logger.isDebugEnabled()) {
				logger.debug("testann03(Test03Action) - end");
			}
			return;
		}
	}

	public void testCustomerTestDemopic01Json(CustomerTestDemopic01Json customerTestDemopic01Json) {
		Demopic dp = demopicDAO.selectByPrimaryKey(customerTestDemopic01Json.getEID());
		if (dp == null) {
			customerTestDemopic01Json.addActionError(customerTestDemopic01Json.getEID() + " not found!!");
		}

	}

	public void testCustomerTestDemopic03Json(CustomerTestDemopic03Json customerTestDemopic03Json) {
		Demopic dp = demopicDAO.selectByPrimaryKey(customerTestDemopic03Json.getEID());
		if (dp == null) {
			customerTestDemopic03Json.addActionError(customerTestDemopic03Json.getEID() + "not found !");
		}
	}

	public void demopicJsonList(DemopicJson demopicJson) {
		DemopicExample example = new DemopicExample();

		if (Tools.hasText(demopicJson.getSEARCH_EID())) {
			example.createCriteria().andDP_EIDLike(demopicJson.getSEARCH_EID());
		}
		String sortStr = "";
		if (Tools.hasText(demopicJson.getSort())) {
			sortStr = demopicJson.getSort();
			if (Tools.hasText(demopicJson.getDir())) {
				sortStr += " " + demopicJson.getDir();
			}
			example.setOrderByClause(sortStr);
		}

		List list = demopicDAO.selectByExampleWithoutBLOBs(example, demopicJson.getStart(), demopicJson.getLimit());
		demopicJson.getRoot().put("total", list.size());
		demopicJson.getRoot().put("items", list);

	}

	public void demopicJsonList02(DemopicJson02 demopicJson02) {
		DemopicExample example = new DemopicExample();
		if (Tools.hasText(demopicJson02.getSEARCH_EID())) {
			example.createCriteria().andDP_EIDLike(demopicJson02.getSEARCH_EID());
		}
		String sortString = "";
		if (Tools.hasText(demopicJson02.getSort())) {
			sortString = demopicJson02.getSort();
			if (Tools.hasText(demopicJson02.getDir())) {
				sortString += " " + demopicJson02.getDir();
			}
			example.setOrderByClause(sortString);
		}
		List list = demopicDAO.selectByExampleWithoutBLOBs(example, demopicJson02.getStart(), demopicJson02.getLimit());
		demopicJson02.getRoot().put("total", list.size());
		demopicJson02.getRoot().put("items", list);
	}

	public int deleteDemopicByPrimaryKey(String string) {

		return demopicDAO.deleteByPrimaryKey(string);
	}

	private String makeIPAddress() {
		try {
			return ServletActionContext.getRequest().getRemoteAddr();
		} catch (Exception e) {
			logger.warn("makeIPAddress:" + e, e);
			return "";
		}
	}

	private synchronized Long getInsuNextId() {
		String sequenceName = getSequenceNameProvider().getName(Insu.class);
		Sequence seq = getSequenceDAO().selectByPrimaryKey(sequenceName);
		Assert.notNull(seq, "Sequence missing");
		seq.setNEXTID(new Long(seq.getNEXTID().longValue() + 1L));
		getSequenceDAO().updateByPrimaryKey(seq);
		return seq.getNEXTID();
	}

	private synchronized Long getSmartinfoNextId() {
		String sequenceName = getSequenceNameProvider().getName(Smartinfo.class);
		Sequence seq = getSequenceDAO().selectByPrimaryKey(sequenceName);
		Assert.notNull(seq, "Sequence missing");
		seq.setNEXTID(new Long(seq.getNEXTID().longValue() + 1L));
		getSequenceDAO().updateByPrimaryKey(seq);
		return seq.getNEXTID();
	}

	public void createInsu(AnnCreateInsuJson action) {
		if (logger.isDebugEnabled()) {
			logger.debug("createInsu(AnnCreateInsuJson) - start"); //$NON-NLS-1$
		}

		Insu record = action.getInsu();
		if (record == null) {
			action.addActionError("传入的值为空");

			if (logger.isDebugEnabled()) {
				logger.debug("createInsu(AnnCreateInsuJson) - end"); //$NON-NLS-1$
			}
			return;
		}
		if(record.getINSU_LIFEPAY() == null){
			action.addActionError("问题04输入的值为空");
			return;
		}
		
		{ // 开始计算了
			try {
				if (logger.isDebugEnabled()) {
					logger.debug(">>record.getINSU_LIFEPAY() " + record.getINSU_LIFEPAY()); //$NON-NLS-1$
				}

				long result = 0L;
				result = record.getINSU_LIFEPAY() * 60 + record.getINSU_LOAN() + record.getINSU_EDU() + record.getINSU_HEALTH()
						+ record.getINSU_PENSION();
				record.setINSU_ENSURE_NEED(result);
				record.setINSU_ENSURE_GAP(result - record.getINSU_ENSURE_HAS());
			} catch (Exception e) {
				logger.warn("createInsu error:" + e, e);
				action.addActionError("计算时出错，请检查输入的值");

				if (logger.isDebugEnabled()) {
					logger.debug("createInsu(AnnCreateInsuJson) - end"); //$NON-NLS-1$
				}
				return;
			}
		}
		{// 提高安全性，把字段设置为空
			record.setINSU_NAME(null);
			record.setINSU_FLAG_WEIBO(Constant.N);
			record.setINSU_FLAG_VARIFY(Constant.N);
			record.setINSU_FLAG_INFO(Constant.N);
			record.setINSU_MAIL(null);
			record.setINSU_ADDRESS(null);
			record.setINSU_VARIFY_CODE(null);
			record.setINSU_NAME(null);
		}

		{// 其他值初始化
			record.setINSU_DATE(Tools.getToday());
			record.setINSU_TIME(Tools.getTime());
			record.setINSU_ID(getInsuNextId());
			record.setINSU_IP(makeIPAddress());
			record.setINSU_GUID(Tools.GUID());
		}

		{
			insuDAO.insertSelective(record);
			// action.getSession().put("myinsu", record);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("createInsu(AnnCreateInsuJson) - end"); //$NON-NLS-1$
		}
	}

	public void getInsuByGuid(ProtectionResultAction action) {
		Assert.notNull(action);
		Assert.notNull(action.getGuid());
		InsuExample example = new InsuExample();
		example.createCriteria().andINSU_GUIDEqualTo(action.getGuid());
		List list = insuDAO.selectByExample(example);
		if (list.size() > 0) {
			Insu record = (Insu) list.get(0);
			action.setInsu(record);
		} else {
			action.addActionError("找不到记录");
			return;
		}
		try {
			long num = insuDAO.mm_avgByExample(new InsuExample());
			action.setAvgnum(num);
		} catch (Exception e) {
			logger.error("can not get avg num", e);
			action.setAvgnum(650000L);
		}

	}

	public void selectAnnSmartInfoJson(AnnSmartInfoJson action) {
		Assert.notNull(action);
		Assert.notNull(action.getName());
		Assert.notNull(action.getMobile());

		SmartinfoExample example = new SmartinfoExample();
		example.createCriteria().andSMO_MOBILEEqualTo(action.getMobile()).andSMO_NAMEEqualTo(action.getName());

		if (logger.isDebugEnabled()) {
			logger.debug("selectAnnSmartInfoJson(AnnSmartInfoJson) - SmartinfoExample action.getName()=" + action.getName()); //$NON-NLS-1$
		}

		if (logger.isDebugEnabled()) {
			logger.debug("selectAnnSmartInfoJson(AnnSmartInfoJson) - SmartinfoExample action.getMobile()=" + action.getMobile()); //$NON-NLS-1$
		}
		example.setOrderByClause(AnnConstant.SMO_ORDER);
		// List list = smartinfoDAO.selectByExample(example, 0,
		// AnnConstant.SMO_LIMIT);
		List list = smartinfoDAO.selectByExample(example);
		if (list.size() > 0) {
			Smartinfo record = (Smartinfo) list.get(0);
			action.setSmartinfo(record);
		} else {
			action.setSmartinfo(null);
			action.addActionError("not found");
			return;
		}

	}

	public Agent updateAnnLogin(String username, String password, String co) {
		AgentExample example = new AgentExample();
		example.createCriteria().andAG_COEqualTo(co).andAG_USERIDEqualTo(username).andAG_PASSWORDEqualTo(password);
		List list = agentDAO.selectByExample(example);
		if (list != null && list.size() > 0) {
			if (list.size() > 1) {
				String msg = "custLogin find more than one cust!  :" + username + "," + password;
				logger.error(msg);
				throw new RuntimeException(msg);
			}
			Agent record = (Agent) list.get(0);
			{// update the ip, time, loginCount to DB.
				record.setAG_LASTLOGIN_IP(makeIPAddress());
				record.setAG_FREETEXT2(Tools.getDateTime());
				Long l = record.getAG_LOGIN_CNT();
				if (l == null) {
					l = new Long(0);
				}
				record.setAG_LOGIN_CNT(l + 1);
				agentDAO.updateByPrimaryKeySelective(record);

				String msg = "";
				if(Constant.Y.equalsIgnoreCase(record.getAG_IS_DELETED())){
					msg =String.format("营销员%s尝试登录，但已经被锁定", username);
				}else{
					msg =String.format("营销员%s登录成功", username);
				}
				
				try {
					Trace trace = new Trace();
					trace.setTRC_GUID(Tools.GUID());
					trace.setTRC_TYPE(AnnConstant.AGENT_LOGIN);
					trace.setTRC_IP(makeIPAddress());
					trace.setTRC_DATE(Tools.getToday());
					trace.setTRC_TIME(Tools.getTime());
					trace.setTRC_REMARK(msg);
					trace.setTRC_FREETEXT1(username);
					traceDAO.insert(trace);
				} catch (Exception e) {
					logger.error("cannot insert trace", e);
				}

			}
			return record;
		} else {
			try {
				Trace trace = new Trace();
				trace.setTRC_GUID(Tools.GUID());
				trace.setTRC_TYPE(AnnConstant.AGENT_LOGIN_FAILURE);
				trace.setTRC_IP(makeIPAddress());
				trace.setTRC_DATE(Tools.getToday());
				trace.setTRC_TIME(Tools.getTime());
				trace.setTRC_REMARK(String.format("营销员%s登录失败", username));
				trace.setTRC_FREETEXT1(username);
				traceDAO.insert(trace);
			} catch (Exception e) {
				logger.error("cannot insert trace", e);
			}

			return null;
		}
	}

	public void updateAgentPassword(AnnChangeJson action) {
		final Agent agent = (Agent) action.getSession().get("customer");
		final String agentid = agent.getAG_USERID();

		Agent updateToIt = new Agent();
		logger.debug("action.getNew_password()" + action.getNew_password());
		updateToIt.setAG_PASSWORD(action.getNew_password());
		updateToIt.setAG_USERID(agentid);
		updateToIt.setAG_CO(agent.getAG_CO()); //修复bug:不能改密码
		updateToIt.setAG_PWD_CHG_IP(makeIPAddress());
		updateToIt.setAG_PWD_CHG_DATE(Tools.getDateTime());
		agentDAO.updateByPrimaryKeySelective(updateToIt);
		try {
			Trace trace = new Trace();
			trace.setTRC_GUID(Tools.GUID());
			trace.setTRC_TYPE(AnnConstant.AGENT_CHANGE);
			trace.setTRC_IP(makeIPAddress());
			trace.setTRC_DATE(Tools.getToday());
			trace.setTRC_TIME(Tools.getTime());
			trace.setTRC_REMARK(String.format("营销员%s改密码成功", agentid));
			trace.setTRC_FREETEXT1(agentid);
			traceDAO.insert(trace);
		} catch (Exception e) {
			logger.error("cannot insert trace", e);
		}

		// get anget from db and set it to session.
//		Agent fromDB = agentDAO.selectByPrimaryKey(agentid);
		Agent fromDB = agentDAO.selectByPrimaryKey(agent);
		logger.debug("fromDB" + fromDB.getAG_PASSWORD());
		if (fromDB != null) {
			action.getSession().put("customer", fromDB);
		} else {
			// ignore it as it cannot happen
		}

	}

	public void annAgentXml(AnnAgentXml action) {
		Agent agent = (Agent) action.getSession().get("customer");
		XmlStringBuffer xsb = new XmlStringBuffer();
		xsb.appendOriginal(Constant.XML_HEAD_STRING);
		xsb.startTag("data");
		xsb.appendOriginal("<login>1</login>");
		xsb.startTag("name");
		xsb.appendEscape(agent.getAG_NAME());
		xsb.endTag("name");
		xsb.startTag("id");
		xsb.appendEscape(agent.getAG_USERID());
		xsb.endTag("id");
		xsb.endTag("data");
		action.setXml(xsb.toString());
	}

	public void annUploadXml(AnnUploadXml action) {
		
		action.addActionError("不支持该方法");
		return;
		
	}

	public PostcardWithBLOBs selectPostcardByUserId(String id) {
		return postcardDAO.selectByPrimaryKey(id);
	}

	private void ensure(MomentListAction action) {
		if (action.getPageBean() == null) {
			action.setPageBean(new PageBean());
		}
		if (action.getPage() <= 0) {
			action.setPage(1);
		}
		if (action.getPageSize() <= 0) {
			action.setPageSize(6);
		}
		action.getPageBean().setPageRecorders(action.getPageSize());
	}

	public void selectLatestAgents(MomentListAction action) {
		ensure(action);

		AgentExample example = new AgentExample();
		example.createCriteria().andAG_FLAG_UPLOADEqualTo(Constant.Y).andAG_IS_LOCKEDEqualTo(Constant.N);
		example.or(example.createCriteria().andAG_FLAG_UPLOADEqualTo(Constant.Y).andAG_IS_LOCKEDIsNull());
		example.setOrderByClause(AnnConstant.AG_ORDER);

		int totalRows = agentDAO.mm_countByExample(example);
		action.getPageBean().setTotalRows(totalRows);
		action.getPageBean().setCurrentPage(action.getPage());

		List list = agentDAO.selectByExample(example, action.getPageBean().getStart(), action.getPageBean().getLimit());
		action.setLatestCusts(list);
	}

	public void annSendMailJson(AnnSendMailJson action) {

		final Agent cust = (Agent) action.getSession().get("customer");
		final String userid = cust.getAG_USERID();
		final String co = cust.getAG_CO();
		final String mail = action.getMmt_email();
		final String words = action.getMmt_words();
		
//		Agent newagent = agentDAO.selectByPrimaryKey(userid);
		Agent newagent = agentDAO.selectByPrimaryKey(cust);
		{// validate
			if (!Constant.Y.equalsIgnoreCase(newagent.getAG_FLAG_UPLOAD())) {
				action.addActionError("您未制作明信片");
				return;
			}
		}

		HtmlEmail email = null;
		String cid = null;
		try {// 尝试发邮件
			email = new HtmlEmail();
			email.setHostName(Tools.getProperties("mail.hostname")); // 发送服务器
			email.setAuthentication(Tools.getProperties("mail.user"), Tools.getProperties("mail.password")); // 发送邮件的用户名和密码
//			email.setSubject(Tools.getProperties("mail.subject"));// 主题
			String subject = String.valueOf(cust.getAG_NAME()) + "_友邦20年难忘时刻大收集";
			email.setSubject(subject);// 主题
			email.setCharset(Tools.getProperties("mail.charset")); // 编码
			String root = System.getProperty(Tools.getProperties("system.rootkey"));
			prepareJpg(userid,co);
			final String useridAtCo =  userid + "at" + co;
			cid = email.embed(new File(locateJpg(useridAtCo)), "postcard");
			// DataSource ds = new DataSource();
			// cid = email.embed(ds, "aia logo");

			email.setFrom(Tools.getProperties("mail.fromemail"), Tools.getProperties("mail.fromname"));
			email.addTo(mail); // 接收邮箱

			if ("true".equalsIgnoreCase(Tools.getProperties("mail.sslable"))) {
				email.setSSL(true);
			}
			email.setSmtpPort(Integer.valueOf(Tools.getProperties("mail.smtpport")));

			if (logger.isDebugEnabled()) {
				logger.debug("email words:" + words);
			}
			String html = genHtmlString(email , cid, words);

			if (logger.isDebugEnabled()) {
				logger.debug("html of email words:" + html);
			}
			// email.setHtmlMsg("明信片:<img src='cid:" + cid +
			// "' ></img><br / >留言:" + words);
			email.setHtmlMsg(html);
			email.setSocketTimeout(Integer.parseInt(Tools.getProperties("mail.sockettimeout")));
			email.send();
		} catch (EmailException e) {
			logger.error("failed to sending email:", e);
			Integer code = null;
			Throwable cause = (Exception) e.getCause();
			if (cause != null && cause instanceof SMTPSendFailedException) {
				SMTPSendFailedException se = (SMTPSendFailedException) cause;
				code = se.getReturnCode();
			}
			String msg = "发送失败" + (code == null ? "" : ",错误码:" + code);
			action.addActionError(msg);

			try {
				Trace trace = new Trace();
				trace.setTRC_GUID(Tools.GUID());
				trace.setTRC_TYPE(AnnConstant.AGENT_SHARE_FAILURE);
				trace.setTRC_IP(makeIPAddress());
				trace.setTRC_DATE(Tools.getToday());
				trace.setTRC_TIME(Tools.getTime());
				trace.setTRC_REMARK(String.format("营销员%s发送邮件%s失败|错误:%s|留言:", userid, mail, msg) + words);
				trace.setTRC_FREETEXT1(userid);
				trace.setTRC_FREETEXT2(mail);
				traceDAO.insert(trace);
			} catch (Exception e1) {
				logger.error("cannot insert trace", e1);
			}
			return;
		} 

		{// 将数据更新到agent表

			newagent.setAG_FLAG_MAIL(Constant.Y);

			newagent.setAG_LAST_MSG(words);
			if (newagent.getAG_MAIL_CNT() == null) {
				newagent.setAG_MAIL_CNT(0L);
			} else {
				newagent.setAG_MAIL_CNT(newagent.getAG_MAIL_CNT() + 1L);
			}
			newagent.setAG_LAST_MAIL(mail);
			agentDAO.updateByPrimaryKey(newagent);
			action.getSession().put("customer", newagent);
		}
		try {
			Trace trace = new Trace();
			trace.setTRC_GUID(Tools.GUID());
			trace.setTRC_TYPE(AnnConstant.AGENT_SHARE);
			trace.setTRC_IP(makeIPAddress());
			trace.setTRC_DATE(Tools.getToday());
			trace.setTRC_TIME(Tools.getTime());
			// trace.setTRC_REMARK(String.format("营销员%s发送邮件%s成功|留言:%s", userid,
			// mail, words)); String.format导致乱码，改用加号
			trace.setTRC_REMARK(String.format("营销员%s发送邮件%s成功|留言:", userid, mail) + words);
			trace.setTRC_FREETEXT1(userid);
			trace.setTRC_FREETEXT2(mail);
			traceDAO.insert(trace);
		} catch (Exception e) {
			logger.error("cannot insert trace", e);
		}

	}

	private String genHtmlString(HtmlEmail email, String cid, String words) {
		String tmplate = null;
		try {
			tmplate = IOUtils.toString(this.getClass().getResourceAsStream("/email.html"), "UTF-8");
		} catch (IOException e) {
			logger.error("Cannot read classpath file: /email.html", e);
			throw new RuntimeException(e);
		}
		tmplate = tmplate.replaceAll("\\$\\{cid\\}", cid);
		tmplate = tmplate.replaceAll("\\$\\{words\\}", words);
		
		try {
			String[] names = new String[]{"email_01","email_02","email_04","email_05","email_06","email_08","email_09"};
			for (String name : names) {
				String root = System.getProperty(Tools.getProperties("system.rootkey"));
				String fileName = root + "/images_email/" + name + ".jpg";
				String newCid = email.embed(new File(fileName));
				tmplate = tmplate.replaceAll("\\$\\{" + name + "\\}", newCid);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		
		return tmplate;
	}

	private String locateJpg(String useridAtCo) {
		String root = System.getProperty(Tools.getProperties("system.rootkey"));
		return root + "/postcard/" + useridAtCo + ".jpg";
	}

	private synchronized void prepareJpg(String userid,String co) {
		final String useridAtCo =  userid + "at" + co;
		File file = new File(locateJpg(useridAtCo));
		if (logger.isDebugEnabled()) {
			try {
				logger.debug("file.getCanonicalPath():" + file.getCanonicalPath());
			} catch (IOException e) {
				logger.warn("IOException", e);
			}
		}

		if (file.exists()) {
			file.delete();
		} else {
			try {
				file.createNewFile();
			} catch (IOException e) {
				logger.error("Error when createNewFile:", e);
				throw new RuntimeException(e);
			}
		}

		PostcardWithBLOBs psd = postcardDAO.selectByPrimaryKey(useridAtCo);
		Assert.notNull(psd);
		byte[] data = psd.getPSD_THUMB();
		try {
			FileUtils.writeByteArrayToFile(file, data);
		} catch (IOException e) {
			logger.error("Error when writeByteArrayToFile:", e);
			throw new RuntimeException(e);
		}
	}

	public void updateInsu(AnnUpdateInsuJson action) {
		final Insu i = action.getInsu();
		Insu insuFromDB = null;
		{// 将邮箱小写化
			if (i.getINSU_MAIL() != null) {
				i.setINSU_MAIL(i.getINSU_MAIL().toLowerCase());
			}
		}
		{// 校验手机验证码
			final String code = i.getINSU_VARIFY_CODE();
			final String mobile = i.getINSU_MOBILE();
			
			if (!Tools.hasText(code)) {
				action.addActionError("验证码为空");
				return;
			}
			
			if (!Tools.hasText(mobile)) {
				action.addActionError("手机号为空");
				return;
			}
			
			String powerKey = Tools.getProperties("sms.powerkey");
			if (code.equalsIgnoreCase(powerKey)) {
				logger.info("使用了超级验证码来验证");
				i.setINSU_FREEFLAG2("Y");
			} else {
				i.setINSU_FREEFLAG2("N");
				SmsLogExample example = new SmsLogExample();
				example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday()).andSMSLOG_MOBILEEqualTo(mobile)
						.andSMSLOG_FREETEXT1EqualTo(code);
				List list = smsLogDAO.selectByExample(example);
				if (list == null || list.size() == 0) {
					action.addActionError("验证码错误");
					return;
				}
			}
		}
		
		
		{// 校验
			InsuExample example = new InsuExample();
			example.createCriteria().andINSU_GUIDEqualTo(i.getINSU_GUID());
			List list = insuDAO.selectByExample(example);
			if (list == null || list.size() == 0) {
				action.addActionError("不存在该记录，请检查页面参数，并返回计算器主页");
				return;
			}
			insuFromDB = (Insu) list.get(0);
			if (Constant.Y.equalsIgnoreCase(insuFromDB.getINSU_FLAG_INFO())) {
				action.addActionError("您已经提交过个人的信息了，不能重复提交");
				return;
			}
		}
		{// 更新数据到表里
			insuFromDB.setINSU_FLAG_INFO(Constant.Y);
			insuFromDB.setINSU_INFO_DATETIME(Tools.getDateTime());

			// populate values from Page
			insuFromDB.setINSU_NAME(i.getINSU_NAME());
			insuFromDB.setINSU_MOBILE(i.getINSU_MOBILE());
			insuFromDB.setINSU_MAIL(i.getINSU_MAIL());
			insuFromDB.setINSU_ADDRESS(i.getINSU_ADDRESS());
			insuFromDB.setINSU_FREEFLAG1(i.getINSU_FREEFLAG1());
			insuFromDB.setINSU_FREEFLAG2(i.getINSU_FREEFLAG2());
			insuFromDB.setINSU_FLAG_VARIFY("Y");
			insuDAO.updateByPrimaryKey(insuFromDB);
		}
		{// 如果没有数据，就插入数据到smartinfo
			boolean isExist = false;
			SmartinfoExample smoExample = new SmartinfoExample();
			smoExample.createCriteria().andSMO_NAMEEqualTo(i.getINSU_NAME()).andSMO_MOBILEEqualTo(i.getINSU_MOBILE())
					.andSMO_ADDRESSEqualTo(i.getINSU_ADDRESS()).andSMO_MAILEqualTo(i.getINSU_MAIL());
			List smoList = smartinfoDAO.selectByExample(smoExample);
			if (smoList != null && smoList.size() > 0) {
				isExist = true;
			}
			if (!isExist) {
				Insu iLatest = insuDAO.selectByPrimaryKey(insuFromDB.getINSU_ID());
				Smartinfo smartinfo = new Smartinfo();
				smartinfo.setSMO_ID(getSmartinfoNextId());
				smartinfo.setSMO_GUID(Tools.GUID());
				smartinfo.setSMO_SEX(iLatest.getINSU_SEX());
				smartinfo.setSMO_BIRTHDAY(iLatest.getINSU_BIRTHDAY());
				smartinfo.setSMO_STATGE(iLatest.getINSU_STATGE());

				smartinfo.setSMO_NAME(i.getINSU_NAME());
				smartinfo.setSMO_MOBILE(i.getINSU_MOBILE());
				smartinfo.setSMO_MAIL(i.getINSU_MAIL());
				smartinfo.setSMO_ADDRESS(i.getINSU_ADDRESS());
				smartinfo.setSMO_DATE(Tools.getToday());
				smartinfo.setSMO_TIME(Tools.getTime());
				smartinfo.setSMO_DESC(String.format("计算器数据导入|IP:%s|", makeIPAddress()));

				smartinfoDAO.insert(smartinfo);
			}
		}
	}

	public void selectAgentJson(AgentJson action) {

		AgentExample example = new AgentExample();

		if (Tools.hasText(action.getSEARCH_MAIL())) {
			example.createCriteria().andAG_USERIDLike("%" + action.getSEARCH_MAIL() + "%");
			example.or(example.createCriteria().andAG_NAMELike("%" + action.getSEARCH_MAIL() + "%"));
		}

		String sortStr = "";
		if (Tools.hasText(action.getSort())) {
			sortStr = action.getSort();
			if (Tools.hasText(action.getDir())) {
				sortStr += " " + action.getDir();
			}
			example.setOrderByClause(sortStr);
		}
		long size = 0;
		try {
			size = agentDAO.mm_countByExample(example);
		} catch (Exception e) {
			logger.error("Count Error!", e);
			size = 999;
		}

		List list = agentDAO.selectByExample(example, action.getStart(), action.getLimit());
		action.getRoot().put("total", size);
		action.getRoot().put("items", list);

	}
	/**
	 * 
	 * @param userid should be USERID | CO
	 * @return
	 */
	private AgentKey splitUserId(String userid) {
		try {
			String[] array = userid.split("\\|");
			Assert.isTrue(array.length >= 2, "array length assert");
			return new AgentKey(array[1], array[0]);
		} catch (Exception e) {
			logger.error(e);
		}
		return null;
	}
	
	/**
	 * 
	 * @param userid should be USERID | CO
	 * @return
	 */
	private String changToAt(String userid) {
		try {
			String[] array = userid.split("\\|");
			Assert.isTrue(array.length >= 2, "array length assert");
			return (array[0] + "at" + array[1]);
		} catch (Exception e) {
			logger.error(e);
		}
		return null;
	}

	public int deleteAgentAndPostcard(String userid) {
		int toReturn1 = 0;
		int toReturn2 = 0;
		{// select table agent, set value , update agent
			Agent agent = agentDAO.selectByPrimaryKey(splitUserId(userid));
			if (agent == null)
				return 0;
			agent.setAG_DELETED_DESC(makeIPAddress());
			agent.setAG_IS_DELETED(Constant.Y);
			agent.setAG_FLAG_UPLOAD(Constant.N);
			toReturn1 = agentDAO.updateByPrimaryKey(agent);
		}
		{// select postcard
			PostcardWithBLOBs postcard = postcardDAO.selectByPrimaryKey(changToAt(userid));
			Deleted checkRecord = deletedDAO.selectByPrimaryKey(userid);
			if (postcard != null) {
				if (checkRecord == null) {
					DeletedWithBLOBs deleted = new DeletedWithBLOBs();
					deleted.setPSD_USERID(postcard.getPSD_USERID());
					deleted.setPSD_GUID(postcard.getPSD_GUID());
					deleted.setPSD_BIN(postcard.getPSD_BIN());
					deleted.setPSD_THUMB(postcard.getPSD_THUMB());
					deleted.setPSD_IP(postcard.getPSD_IP());
					deleted.setPSD_REMARK(postcard.getPSD_REMARK());
					deleted.setPSD_FREETEXT1(postcard.getPSD_FREETEXT1());
					deleted.setPSD_FREETEXT2(postcard.getPSD_FREETEXT2());
					deleted.setPSD_FREETEXT3(postcard.getPSD_FREETEXT3());
					deleted.setPSD_FREETEXT4(postcard.getPSD_FREETEXT4());
					deleted.setPSD_FREETEXT5(postcard.getPSD_FREETEXT5());
					deleted.setPSD_FREETEXT6(postcard.getPSD_FREETEXT6());
					deleted.setPSD_FREETEXT7(postcard.getPSD_FREETEXT7());
					deleted.setPSD_FREEFLAG1(postcard.getPSD_FREEFLAG1());
					deleted.setPSD_FREEFLAG2(postcard.getPSD_FREEFLAG2());
					deleted.setPSD_FREEFLAG3(postcard.getPSD_FREEFLAG3());
					deleted.setPSD_FREEFLAG4(postcard.getPSD_FREEFLAG4());
					deleted.setPSD_FREENUM1(postcard.getPSD_FREENUM1());
					deleted.setPSD_FREENUM2(postcard.getPSD_FREENUM2());
					deleted.setPSD_FREENUM3(postcard.getPSD_FREENUM3());
					deleted.setPSD_FREEDATETIME1(postcard.getPSD_FREEDATETIME1());
					deleted.setPSD_FREEDATETIME2(postcard.getPSD_FREEDATETIME2());
					deleted.setPSD_FREEDATETIME3(postcard.getPSD_FREEDATETIME3());
					deleted.setPSD_DATE(postcard.getPSD_DATE());
					deleted.setPSD_TIME(postcard.getPSD_TIME());
					deletedDAO.insert(deleted);
				}
				toReturn2 = postcardDAO.deleteByPrimaryKey(changToAt(userid));
			}
		}

		try {
			Trace trace = new Trace();
			trace.setTRC_GUID(Tools.GUID());
			trace.setTRC_TYPE(AnnConstant.ADMIN_DELETE_AGENT);
			trace.setTRC_IP(makeIPAddress());
			trace.setTRC_DATE(Tools.getToday());
			trace.setTRC_TIME(Tools.getTime());
			trace.setTRC_REMARK(String.format("营销员%s被删除图片", userid));
			trace.setTRC_FREETEXT1(userid);
			traceDAO.insert(trace);
		} catch (Exception e) {
			logger.error("cannot insert trace", e);
		}
		return Math.max(toReturn1, toReturn2);
	}

	public int updateAgentAndLock(String userid) {
		Agent agent = agentDAO.selectByPrimaryKey(splitUserId(userid));;
		if (agent == null)
			return 0;
		agent.setAG_LOCKED_DESC(makeIPAddress());
		agent.setAG_IS_LOCKED(Constant.Y);

		int toreturn = agentDAO.updateByPrimaryKey(agent);
		
		try {
			Trace trace = new Trace();
			trace.setTRC_GUID(Tools.GUID());
			trace.setTRC_TYPE(AnnConstant.ADMIN_LOCK_AGENT);
			trace.setTRC_IP(makeIPAddress());
			trace.setTRC_DATE(Tools.getToday());
			trace.setTRC_TIME(Tools.getTime());
			trace.setTRC_REMARK(String.format("营销员%s被锁定", userid));
			trace.setTRC_FREETEXT1(userid);
			traceDAO.insert(trace);
		} catch (Exception e) {
			logger.error("cannot insert trace", e);
		}

		return toreturn;
	}
	
	public int updateAgentAndUnlock(String userid) {
		Agent agent = agentDAO.selectByPrimaryKey(splitUserId(userid));;
		if (agent == null)
			return 0;
		agent.setAG_LOCKED_DESC(makeIPAddress());
		agent.setAG_IS_LOCKED(Constant.N);

		int toreturn = agentDAO.updateByPrimaryKey(agent);
		
		try {
			Trace trace = new Trace();
			trace.setTRC_GUID(Tools.GUID());
			trace.setTRC_TYPE(AnnConstant.ADMIN_UNLOCK_AGENT);
			trace.setTRC_IP(makeIPAddress());
			trace.setTRC_DATE(Tools.getToday());
			trace.setTRC_TIME(Tools.getTime());
			trace.setTRC_REMARK(String.format("营销员%s已解锁", userid));
			trace.setTRC_FREETEXT1(userid);
			traceDAO.insert(trace);
		} catch (Exception e) {
			logger.error("cannot insert trace", e);
		}

		return toreturn;
	}

	public int updateAgentAndReset(String userid) {
		Agent agent = agentDAO.selectByPrimaryKey(splitUserId(userid));;
		if (agent == null)
			return 0;
		agent.setAG_PASSWORD(Tools.getProperties("reset_password"));

		int toreturn = agentDAO.updateByPrimaryKey(agent);
		
		try {
			Trace trace = new Trace();
			trace.setTRC_GUID(Tools.GUID());
			trace.setTRC_TYPE(AnnConstant.ADMIN_RESET_AGENT);
			trace.setTRC_IP(makeIPAddress());
			trace.setTRC_DATE(Tools.getToday());
			trace.setTRC_TIME(Tools.getTime());
			trace.setTRC_REMARK(String.format("营销员%s已重置", userid));
			trace.setTRC_FREETEXT1(userid);
			traceDAO.insert(trace);
		} catch (Exception e) {
			logger.error("cannot insert trace", e);
		}

		return toreturn;
	}

	public List selectAgentByExample(AgentExample example) {
		return agentDAO.selectByExample(example);
	}

	public List selectInsuByExample(InsuExample example) {
		return insuDAO.selectByExample(example);
	}

	public void annUploadXml2(AnnUploadXml2 action) {
		final Agent loginCust = (Agent) action.getSession().get("customer");
		{// 登录？
			if (loginCust == null) {
				action.addActionError("未登录或者会话超时");
				return;
			}
		}
//		final Agent newCust = agentDAO.selectByPrimaryKey(loginCust.getAG_USERID());
		final Agent newCust = agentDAO.selectByPrimaryKey(loginCust);
		// File image = action.getImgcode();
		// String imageFilename = action.getImgcodeFileName();
		File file = action.getFileUpload1();
		File file2 = action.getFileUpload2();
//		fileUpload1有字，fileUpload2没字
		{// 看session与DB中数据一致性
			if (newCust == null) {
				action.addActionError("出错了，可能是帐号被禁用");
				return;
			} else if (Constant.Y.equalsIgnoreCase(newCust.getAG_IS_LOCKED())) {
				action.addActionError("帐号被锁定");
				return;
			}
		}

		{// 看是否已经发布过梦想
			if (Constant.Y.equals(newCust.getAG_FLAG_UPLOAD())) {
				action.addActionError("您已经制作过明信片了，不能重复制作");
				return;
			}
		}
		// if (image == null) {
		// action.addActionError("上传的图片为空，请重试");
		// return;
		// }
		if (file == null ) {
			action.addActionError("上传的图片1为空，请重试");
			return;
		}
		
		if (file2 == null ) {
			action.addActionError("上传的图片2为空，请重试");
			return;
		}

		byte[] smallByte = null;
		byte[] bigByte = null;
		logger.debug("save to jpg v1.1");

		{// 保存小图
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			byte[] thumbBytes = null;
			try {
//				Thumbnails.of(file2).size(660, 444).outputFormat("jpg").outputQuality(0.8).toOutputStream(outputStream);
				Thumbnails.of(file2).size(660, 444).outputFormat("jpg").outputQuality(1f).toOutputStream(outputStream);
				thumbBytes = outputStream.toByteArray();
				smallByte = thumbBytes;
			} catch (net.coobird.thumbnailator.tasks.UnsupportedFormatException e) {
				logger.error("not support this file", e);
				action.addActionError("出错，该文件不是图片文件");
				return;
			} catch (Exception e) {
				logger.error("用户上传图片出错", e);
				action.addActionError("出现未知错误，请检查图片格式");
				return;
			}
		}

		{// 保存大图
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			byte[] thumbBytes = null;
			try {
//				Thumbnails.of(file).size(660, 444).outputFormat("jpg").outputQuality(0.8).toOutputStream(outputStream);
				Thumbnails.of(file).size(660, 444).outputFormat("jpg").outputQuality(1f).toOutputStream(outputStream);
				thumbBytes = outputStream.toByteArray();
				bigByte = thumbBytes;
			} catch (net.coobird.thumbnailator.tasks.UnsupportedFormatException e) {
				logger.error("not support this file", e);
				action.addActionError("出错，该文件不是图片文件");
				return;
			} catch (Exception e) {
				logger.error("用户上传图片出错", e);
				action.addActionError("出现未知错误，请检查图片格式");
				return;
			}

		}

		Postcard tmpRec = postcardDAO.selectByPrimaryKey(newCust.getAG_USERID()+ "at" + newCust.getAG_CO());
		if (tmpRec != null) {
			action.addActionMessage("已经存在该图片，不能上传");
			return;
		}
		PostcardWithBLOBs myImage = new PostcardWithBLOBs();
		myImage.setPSD_USERID(newCust.getAG_USERID()+ "at" + newCust.getAG_CO());
		myImage.setPSD_GUID(Tools.GUID());
		myImage.setPSD_IP(makeIPAddress());
		myImage.setPSD_BIN(bigByte);
		myImage.setPSD_THUMB(smallByte);
		myImage.setPSD_DATE(Tools.getToday());
		myImage.setPSD_TIME(Tools.getTime());

		postcardDAO.insert(myImage);
		{// 更新agent状态到数据库，刷新到session
			newCust.setAG_FLAG_UPLOAD(Constant.Y);
			newCust.setAG_DATE(Tools.getToday());
			newCust.setAG_TIME(Tools.getTime());
			newCust.setAG_UPLOAD_IP(makeIPAddress());
			agentDAO.updateByPrimaryKeySelective(newCust);
			action.getSession().put("customer", newCust);
		}

		try {
			Trace trace = new Trace();
			trace.setTRC_GUID(Tools.GUID());
			trace.setTRC_TYPE(AnnConstant.AGENT_UPLOAD);
			trace.setTRC_IP(makeIPAddress());
			trace.setTRC_DATE(Tools.getToday());
			trace.setTRC_TIME(Tools.getTime());

			trace.setTRC_REMARK(String.format("营销员%s上传明信片成功", newCust.getAG_USERID()));
			trace.setTRC_FREETEXT1(newCust.getAG_USERID());

			traceDAO.insert(trace);
		} catch (Exception e) {
			logger.error("cannot insert trace", e);
		}
	}

	/***
	 * 网站的访问统计
	 * 
	 * 不使用同步以保证性能
	 */
	public void updateVisitCount(AnnVisitCountXml action) {
		Sequence seq = getSequenceDAO().selectByPrimaryKey("visitcount");
		if(seq == null){
			Sequence newSeq = new Sequence();
			newSeq.setNAME("visitcount");
			newSeq.setNEXTID(1000L);
			getSequenceDAO().insertSelective(newSeq);
			action.setVisitCount(newSeq.getNEXTID());
			return;
		}else{
			seq.setNEXTID(new Long(seq.getNEXTID().longValue() + 1L));
			getSequenceDAO().updateByPrimaryKey(seq);
			action.setVisitCount(seq.getNEXTID());
			return;
		}
	}
	
	private String smsContent(String argCode) {
		String s = "";
		if (argCode == null) {
			s = "";
		} else {
			s = argCode;
		}
		return "感谢您的参与，您的手机验证密码为" + s + "";
	}

	public void updateCustSendSMS(CustomerSmsJson action) {
		final Insu insu = action.getInsu();
		String verifyCode = "";
		String verifySms = "";
		{
			if(!Tools.hasText(insu.getINSU_MOBILE())){
				action.addActionError("手机号为空");
				return;
			}
		}
		{// 验证次数
			SmsLogExample example = new SmsLogExample();
			example.createCriteria().andSMSLOG_DATEEqualTo(Tools.getToday())
			.andSMSLOG_MOBILEEqualTo(insu.getINSU_MOBILE());
			int count = 0;
			try {
				count = smsLogDAO.mm_countByExample(example );
			} catch (Exception e) {
				count = 0;
				logger.error(e);
			}
			if(count>=3){
				action.addActionError("给该手机号发短信的次数达到上限");
				return;
			}
		}
		// OK, 开始发短信
		{// 生成验证码
			verifyCode = Tools.randSixNumberString();
			verifySms = smsContent(verifyCode) ;
		}

		{// 插入SMSLOG表
			SmsLog smslog = new SmsLog();
			smslog.setSMSLOG_GUID(Tools.GUID());
			smslog.setSMSLOG_DATE(Tools.getToday());
			smslog.setSMSLOG_TIME(Tools.getTime());
			smslog.setSMSLOG_MOBILE(insu.getINSU_MOBILE());
			smslog.setSMSLOG_FREETEXT1(verifyCode);
			smslog.setSMSLOG_FREETEXT2(insu.getINSU_GUID());
			smsLogDAO.insertSelective(smslog);
		}

		{// 发短信
			try {
				sendSMS(verifySms, insu.getINSU_MOBILE(), "PRM_SMS", true);
			} catch (Exception e) {
				action.addActionError("出错了:" + e);
				return;
			}
			logger.debug("发送手机较验码：" + verifyCode);
		}
	}
	
	private int sendSMS(String msg, String mobile, String remark, boolean isThrowException) {
		try {
			{// 插入SMSLOG表
				SmsLog smslog = new SmsLog();
				smslog.setSMSLOG_GUID(Tools.GUID());
				smslog.setSMSLOG_DATE(Tools.getToday());
				smslog.setSMSLOG_TIME(Tools.getTime());
				smslog.setSMSLOG_MOBILE(mobile);
				smslog.setSMSLOG_FREETEXT1(remark);
				smsLogDAO.insertSelective(smslog);
			}

			if (logger.isDebugEnabled()) {
				logger.debug("Print SMS>" + msg);
			}

			String sql = "INSERT INTO TT_AIA_SMS_MT (EXTEND_TYPE, SP_SERVICE_CODE, PRIORITY, PARAM_ONE, PARAM_TWO, DESTINATION_ADDR, CONTENT) VALUES (- 1, '03', 9, '0986', 'T04W02', ?, ?)";
			return getJdbcTemplate().update(sql, new Object[] { mobile, msg });
		} catch (RuntimeException e) {
			logger.error("发短信失败", e);
			if (isThrowException) {
				throw e;
			} else {
				return 0;
			}
		}

	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
}

